/**
 * 特定材质检查工具
 * 专门检查指定材质的详细设置
 */

export class SpecificMaterialChecker {
    /**
     * 检查指定名称的材质
     * @param {THREE.Scene} scene - Three.js场景对象
     * @param {string} materialName - 材质名称
     */
    static checkMaterialByName(scene, materialName) {
        console.log(`\n🔍 详细检查材质: "${materialName}"\n`);
        
        const foundMaterials = [];
        
        scene.traverse((obj) => {
            if (obj.isMesh && obj.material) {
                const materials = Array.isArray(obj.material) ? obj.material : [obj.material];
                
                materials.forEach((mat, index) => {
                    // 检查材质名称匹配
                    const matName = mat.userData?.materialName || mat.name || '';
                    if (matName.includes(materialName) || obj.name.includes(materialName)) {
                        foundMaterials.push({
                            mesh: obj,
                            material: mat,
                            materialIndex: index
                        });
                    }
                });
            }
        });
        
        if (foundMaterials.length === 0) {
            console.log(`❌ 未找到材质: "${materialName}"`);
            return null;
        }
        
        console.log(`✅ 找到 ${foundMaterials.length} 个匹配的材质:\n`);
        
        foundMaterials.forEach((item, index) => {
            const { mesh, material, materialIndex } = item;
            
            console.log(`━━━ 材质 ${index + 1} ━━━`);
            console.log(`Mesh名称: ${mesh.name || '(unnamed)'}`);
            console.log(`材质索引: ${materialIndex}`);
            console.log(`材质类型: ${material.type}`);
            console.log(`材质名称: ${material.name || '(unnamed)'}`);
            console.log(`userData.materialName: ${material.userData?.materialName || '(无)'}`);
            
            // 🎯 关键属性检查
            console.log(`\n🎨 颜色和透明属性:`);
            console.log(`   color: RGB(${material.color.r.toFixed(3)}, ${material.color.g.toFixed(3)}, ${material.color.b.toFixed(3)})`);
            console.log(`   opacity: ${material.opacity}`);
            console.log(`   transparent: ${material.transparent}`);
            console.log(`   alphaTest: ${material.alphaTest}`);
            
            // 🎯 深度和混合属性
            console.log(`\n🔧 渲染属性:`);
            console.log(`   depthWrite: ${material.depthWrite}`);
            console.log(`   depthTest: ${material.depthTest}`);
            console.log(`   depthFunc: ${material.depthFunc}`);
            console.log(`   blending: ${material.blending} (${this.getBlendingName(material.blending)})`);
            console.log(`   side: ${material.side} (${this.getSideName(material.side)})`);
            
            // 🎯 贴图信息
            console.log(`\n🖼️ 贴图信息:`);
            console.log(`   map: ${!!material.map} ${material.map ? `(${material.map.image?.src || '未知'})` : ''}`);
            console.log(`   alphaMap: ${!!material.alphaMap} ${material.alphaMap ? `(${material.alphaMap.image?.src || '未知'})` : ''}`);
            console.log(`   normalMap: ${!!material.normalMap}`);
            console.log(`   roughnessMap: ${!!material.roughnessMap}`);
            console.log(`   metalnessMap: ${!!material.metalnessMap}`);
            
            // 🎯 PBR属性
            if (material.metalness !== undefined || material.roughness !== undefined) {
                console.log(`\n⚡ PBR属性:`);
                console.log(`   metalness: ${material.metalness}`);
                console.log(`   roughness: ${material.roughness}`);
            }
            
            // 🎯 Mesh渲染属性
            console.log(`\n🎭 Mesh渲染属性:`);
            console.log(`   renderOrder: ${mesh.renderOrder}`);
            console.log(`   frustumCulled: ${mesh.frustumCulled}`);
            console.log(`   castShadow: ${mesh.castShadow}`);
            console.log(`   receiveShadow: ${mesh.receiveShadow}`);
            
            // 🎯 问题诊断
            console.log(`\n🔍 问题诊断:`);
            const issues = [];
            
            if (material.color.r === 0 && material.color.g === 0 && material.color.b === 0) {
                issues.push('材质颜色为纯黑色');
            }
            
            if (material.transparent && material.depthWrite) {
                issues.push('透明材质启用了depthWrite，可能导致渲染问题');
            }
            
            if (!material.transparent && material.alphaTest === 0 && (material.map || material.alphaMap)) {
                issues.push('有贴图但未启用透明或alphaTest');
            }
            
            if (material.blending !== 1) { // THREE.NormalBlending = 1
                issues.push(`使用了非标准混合模式: ${this.getBlendingName(material.blending)}`);
            }
            
            if (issues.length > 0) {
                issues.forEach(issue => console.log(`   ⚠️ ${issue}`));
            } else {
                console.log(`   ✅ 未发现明显问题`);
            }
            
            console.log('\n');
        });
        
        return foundMaterials;
    }
    
    /**
     * 获取混合模式名称
     */
    static getBlendingName(blending) {
        const blendingNames = {
            0: 'NoBlending',
            1: 'NormalBlending',
            2: 'AdditiveBlending',
            3: 'SubtractiveBlending',
            4: 'MultiplyBlending',
            5: 'CustomBlending'
        };
        return blendingNames[blending] || `Unknown(${blending})`;
    }
    
    /**
     * 获取面渲染模式名称
     */
    static getSideName(side) {
        const sideNames = {
            0: 'FrontSide',
            1: 'BackSide',
            2: 'DoubleSide'
        };
        return sideNames[side] || `Unknown(${side})`;
    }
}

// 创建便捷实例
const specificMaterialChecker = {
    check: (materialName) => {
        const scene = window.manager?.getCurrentScene()?.scene;
        if (!scene) {
            console.error('❌ 场景未加载');
            return;
        }
        return SpecificMaterialChecker.checkMaterialByName(scene, materialName);
    }
};

// 暴露到全局
window.specificMaterialChecker = specificMaterialChecker;

export default specificMaterialChecker;
